package com.luca.sl651server.client.tcp.handler;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.binary.Hex;

/**
 * 客户端处理
 */
@Slf4j
public class TcpNettyClientHandler extends SimpleChannelInboundHandler {

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        String data =
            "7E7E010004230024A002340042020061240509153414F1F1000423002448F0F024050915343B23004677902221000000002021000000002631000000000220F0F024050908001F230000000038121175035813";
        data += data;
        ByteBuf byteBuf = Unpooled.copiedBuffer(Hex.decodeHex(data));
        ctx.writeAndFlush(byteBuf);
        log.debug("tcp netty client send msg id>>>" + ctx.channel().id().toString());
    }

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, Object msg) throws Exception {
        ByteBuf buf = (ByteBuf)msg;
        byte[] buffer = new byte[buf.readableBytes()];
        buf.readBytes(buffer);
        log.debug("tcp netty client receive msg id>>>" + ctx.channel().id().toString() + " msg content>>>"
            + new String(buffer));
    }
}
